package org.dei.perla.sys;

import java.util.ArrayList;

import org.dei.dataserver.Server;
import org.dei.perla.parser.QueryExecutionAgent;
import org.dei.perla.parser.QueryParserAgent;
import org.dei.perla.rockfall.utils.DatabaseDump;
import org.dei.perla.rockfall.utils.IntecDatabaseDump;
import org.dei.perla.sys.console.core.ConsoleServer;
import org.dei.perla.sys.device.fpc.FPC;
import org.dei.perla.sys.device.fpc.dspic.DSPicFPC;
import org.dei.perla.sys.device.fpc.intec.IntecFpc;
import org.dei.perla.utils.PerlaEnv;
import org.dei.perla.utils.PerlaRuntime;
import org.dei.perla.utils.logger.ConsoleLogger;
import org.dei.perla.utils.logger.Logger;
import org.dei.perla.utils.logger.LogRecord.Verbosity;

public class PerlaMain {

	private static int MAX_FPC, SERVER_PORT;
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		//da modificare nella release 2.x
		ArrayList<FPC> fpcList;
		//da modificare nella release 2.x
		Server connectionServer;

		PerlaEnv.init();
		PerlaRuntime.init();
		
		Logger logger = new ConsoleLogger();
		logger.setVerbosity(Verbosity.High);
		logger.start();
		
		//da modificare nella release 2.x
		connectionServer = PerlaMain.spawnConnectionServer();
		connectionServer.start();

		//da modificare nella release 2.x
		fpcList = PerlaMain.createFPCList(connectionServer);

		ConsoleServer server = new ConsoleServer();
		
		QueryParserAgent queryParserAgent = QueryParserAgent.getDefault();
		queryParserAgent.setQueryToParsePipe(server.getQueryToParsePipe());
		QueryExecutionAgent queryExecutionAgent = QueryExecutionAgent.getDefault();
		QueryExecutionAgent.setFPCList(fpcList);
		queryExecutionAgent.setQueryToExecutePipe(QueryParserAgent.getQueryPipe());
		
		server.start();
		
	}

	private static Server spawnConnectionServer() {
		Server server;
		PerlaRuntime runtime = PerlaRuntime.getDefaultRuntime();
		if(runtime.containsKey("SERVER_PORT")){
			SERVER_PORT = new Integer(runtime.getProperty("SERVER_PORT"));			
		}
		else {
			SERVER_PORT = 5606;
		}
		server = new Server(SERVER_PORT);
		return server;
	}

	private static ArrayList<FPC> createFPCList(Server connectionServer) {
		ArrayList<FPC> fpcList = new ArrayList<FPC>();
		PerlaRuntime runtime = PerlaRuntime.getDefaultRuntime();
		if(runtime.containsKey("DSPIC_NUM")){
			MAX_FPC = new Integer(runtime.getProperty("DSPIC_NUM")) + 1;			
		}
		else {
			MAX_FPC = 8;
		}
		IntecFpc intecFpc = new  IntecFpc(connectionServer.getFpcPipes(0));
		fpcList.add(intecFpc);
		Thread intecDbDump = new Thread(new IntecDatabaseDump(intecFpc.registerQuery(null)));
		intecDbDump.start();
		
		// Istanzio ed aggancio le fpc al server ed al database dumper
		for (int i = 1; i < MAX_FPC; i++){
			DSPicFPC tTempFpc = new DSPicFPC(connectionServer.getFpcPipes(i), i);
			fpcList.add(tTempFpc);
			Thread dbDump = new Thread(new DatabaseDump(tTempFpc.registerQuery(null)));
			dbDump.start();
		}
		return fpcList;
	}

}
